// pages/orders/orders.js
let app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,  // 当前选中的标签页索引
    orders: [],     // 订单列表
    tokenString: "", // 用户token
  },
  
  formatTime(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取token
    wx.getStorage({
      key: "_token",
      success: res => {
        this.setData({
          tokenString: res.data
        });
        // 加载订单数据
        this.loadOrders(this.data.activeTab);
      },
      fail: err => {
        wx.navigateTo({
          url: '../login/login',
        });
      }
    });
  },

  /**
   * 标签页切换事件
   */
  onTabChange(event) {
    const activeTab = event.detail.index;
    this.setData({ activeTab });
    this.loadOrders(activeTab);
  },

  /**
   * 加载订单数据
   * @param {number} status - 订单状态：0全部，1进行中，2已完成
   */
  loadOrders(status) {
    wx.showLoading({
      title: '加载中...',
    });

    wx.request({
      url: 'https://kf.webxyq.com/findOrder',
      method: 'GET',
      data: {
        appkey: app.globalData.appkey,
        tokenString: this.data.tokenString,
        status: status
      },
      success: res => {
        const orders = res.data.result.map(order => ({
          ...order,
          formattedTime: this.formatTime(order.createdAt) // 添加格式化后的时间字段
        }));
        this.setData({ orders });
        console.log(res);
        wx.hideLoading();
        if (res.statusCode === 200) {
          // 处理订单数据
          // 按oid分组订单商品
          const orderMap = new Map();
          (res.data.result || []).forEach(item => {
            if (!orderMap.has(item.oid)) {
              orderMap.set(item.oid, {
                oid: item.oid,
                createdAt: item.createdAt,
                status: item.status,
                products: [],
                totalCount: 0,
                totalPrice: 0
              });
            }
            const order = orderMap.get(item.oid);
            order.products.push(item);
            order.totalCount += item.count;
            order.totalPrice += item.price * item.count;
          });
          
          this.setData({ 
            orders: Array.from(orderMap.values())
          });
        } else {
          this.setData({ orders: [] });
          wx.showToast({
            title: res.data.msg || '获取订单失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 确认收货
   */
  onReceiveOrder(event) {
    const oid = event.currentTarget.dataset.oid;
    
    wx.showModal({
      title: '确认收货',
      content: '请确认已收到商品',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' });
          
          wx.request({
            url: 'https://kf.webxyq.com/receive',
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            data: {
              appkey: app.globalData.appkey,
              tokenString: this.data.tokenString,
              oid: oid
            },
            success: res => {
              if (res.statusCode === 200) {
                // 更新本地订单状态
                const updatedOrders = this.data.orders.map(order => {
                  if (order.oid === oid) {
                    return { ...order, status: 2 };
                  }
                  return order;
                });
                
                this.setData({ orders: updatedOrders });
                wx.showToast({ title: '收货成功' });
              }
            },
            fail: err => {
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 删除订单
   */
  onDeleteOrder(event) {
    const oid = event.currentTarget.dataset.oid;
    const order = this.data.orders.find(item => item.oid === oid);
  
    // 添加状态检查
    if (order.status === 1) {
      wx.showToast({
        title: '请先确认收货',
        icon: 'none'
      });
      return;
    }
  
    wx.showModal({
      title: '删除订单',
      content: '确定要删除此订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          });
          
          wx.request({
            url: 'https://kf.webxyq.com/removeOrder',
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            data: {
              appkey: app.globalData.appkey,
              tokenString: this.data.tokenString,
              oid: oid
            },
            success: res => {
              wx.hideLoading();
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新加载订单数据
                this.loadOrders(this.data.activeTab);
              } else {
                wx.showToast({
                  title: res.data.msg || '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: err => {
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.tokenString) {
      this.loadOrders(this.data.activeTab);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadOrders(this.data.activeTab);
    wx.stopPullDownRefresh();
  }
});